import gl.java.umsp.room.RoomServiceConfig;
import gl.java.util.TextUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;

import javax.xml.soap.Text;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;


public class RebootPlayer extends gl.java.umsp.websocket.RouteBase implements gl.java.umsp.websocket.IHttpController {

    public RebootPlayer() {

    }

    @Override
    public boolean onHttpRequest(FullHttpRequest request, DefaultFullHttpResponse rsp, ChannelHandlerContext ctx) {
        rsp.setStatus(HttpResponseStatus.NOT_FOUND);
        rsp.headers().set(HttpHeaders.Names.CONTENT_TYPE,
                "text/html");
        String IP = GameConfig.RoomServerIP;
        int gameID = 0;
        try {
            URI uri = new URI(request.getUri());
            Map<String, String> map = paramToMap(uri.getQuery());
            if (map.containsKey(IP)) {
                IP = map.get("IP");
            }
            if (map.containsKey(gameID)) {
                gameID = Integer.parseInt(map.get("gameID"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return return500(request, rsp, ctx, e);
        }
        RoomServiceConfig config = RoomServiceApplication.getInstance().reg(IP, gameID);
        ByteBuf responseBuf = Unpooled.copiedBuffer(config.toString(), CharsetUtil.UTF_8);
        rsp.content().writeBytes(responseBuf);
        handKeepLive(request, rsp);
        ctx.writeAndFlush(rsp);
        responseBuf.release();
        return true;
    }

    public static java.util.Map<String, String> paramToMap(String paramStr) {
        java.util.Map<String, String> resMap = new HashMap();
        if (TextUtil.isNotEmpty(paramStr)) {
            String[] params = paramStr.split("&");
            for (int i = 0; i < params.length; i++) {
                String[] param = params[i].split("=");
                if (param.length >= 2) {
                    String key = param[0];
                    String value = param[1];
                    for (int j = 2; j < param.length; j++) {
                        value += "=" + param[j];
                    }
                    resMap.put(key, value);
                }
            }
        }
        return resMap;
    }
}
